package com.geecg.hb.dbhandle;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.geecg.hb.annotation.Column;
import com.geecg.hb.bean.ConnectonBean;
import com.geecg.hb.util.ParseJDBCParams;

public class HandleDB<T> {
	private Connection conn=null;
	private ConnectonBean bean=ParseJDBCParams.perseXML(null);
	
	/**
	 * 获取数据库连接
	 * */
	public void getConnection(){
		try {
			Class.forName(bean.getDriverClassName());
			conn= DriverManager.getConnection(bean.getUrl(),bean.getUsername(),bean.getPassword());
		} catch (SQLException | ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 创建连接，我也不知道是干嘛的。
	 * */
	public Statement getStatement(){
		getConnection();
		Statement statement=null;
		try {
			statement= conn.createStatement();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return statement;
	}
	
	/***
	 * 查询Sql语句,返回查询的list集合
	 * */
	public List<T> query(String sql,Class<T> clazz){
		Statement statement=getStatement();
		ResultSet rs=null;
		List<T> list=null;
		try {
			rs = statement.executeQuery(sql);
			list=resultTurnEntity(rs, clazz);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}
	/**
	 * 执行更改语句
	 * */
	public int update(String sql) {
		Statement statement=getStatement();
		int i=0;
		try {
			i = statement.executeUpdate(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    return i;
	}
	
	/**
	 * 将数据库返回的结果转变为实体加入到List集合后返回
	 * */
	public List<T> resultTurnEntity(ResultSet rs,Class<T> clazz){
		List<T> list=new ArrayList<T>();
		try {
			Field[] fields= null;
			String columnName=null;//真实的名称，数据库字段名称
			while(rs.next()){
				T t=clazz.newInstance();
				fields=clazz.getDeclaredFields();
				for (Field field : fields) {
					 boolean flag = field.isAccessible();
					//如果有注释，则使用注释
					if(field.isAnnotationPresent(Column.class)){
						columnName= field.getAnnotation(Column.class).name();
					}else{
						columnName= field.getName();
					}
					field.setAccessible(true); //强制访问打开
					field.set(t,rs.getObject(columnName));//为字段赋值
					field.setAccessible(flag); //强制访问关闭
				}
				list.add(t);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}
 
	/**
	 * 将数据库返回的结果转变为map，然后将map加入到List中返回
	 * */
	public List<Object> resultTurnMap(ResultSet rs){
		List<Object> list=new ArrayList<Object>();
		Map<String,String> entityMap=null;
		Map<String,String> map=getEntityFieldsByMap(rs);
		try {
			while(rs.next()){
				entityMap=new HashMap<String,String>();
				//获取列信息
				for (Map.Entry<String, String> entry : map.entrySet()) {
					entityMap.put(entry.getKey(),(String) rs.getObject(entry.getValue()));
				}
				list.add(entityMap);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}
	
	/**
	 *获取数据库返回的字段列表名称 
	 * */
	public Map<String,String> getEntityFieldsByMap(ResultSet rs){
		Map<String,String> map=new HashMap<String,String>();
		String field = null;
		try {
			ResultSetMetaData m=rs.getMetaData();
			for(int i=1;i<=m.getColumnCount();i++){
				field = normalizeColumnField(m.getColumnName(i));
				map.put(field, m.getColumnName(i));
			 }
		}catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return map;
	}
	/**
	 * 根据规则返回与实体类型一样的名称，目前先不实现。
	 * */
	public String normalizeColumnField(String fieldName){
		return fieldName;
	}
	
} 


